from .image_convert_base import ConvertBase
import numpy as np
import cv2 as cv


class PaddingResizeConvert(ConvertBase):
    
    def __init__(self, target_size, use_rate = 0.5, padding_value = 0):
        super().__init__(use_rate)
    
        self.targetsize = target_size
        self.padding_value = padding_value
        
        
    def convert(self, img, boxes, points):
        old_h,old_w, _ = img.shape
        new_w, new_h = self.targetsize
        #求出比例
        scale_x, scale_y = new_w / old_w, new_h / old_h
        min_scale = min(scale_x, scale_y)
        old_w, old_h = int(old_w * min_scale), int(old_h * min_scale)
        img = cv.resize(img, (old_w, old_h))
        append_w = int((new_w - old_w) / 2.0)
        append_h = int((new_h - old_h) / 2.0)
        #创建目标数据
        img_new = np.zeros([new_h, new_w, 3], np.uint8)
        img_new[:, :] = self.padding_value
        #缩放后的图像
        img_new[append_h:append_h + old_h, append_w : append_w + old_w] = img
        if boxes is not None:
            #缩放
            boxes =boxes.astype(np.float32) * min_scale
            boxes[:, [0, 2]] += append_w
            boxes[:, [1, 3]] += append_h
            boxes = boxes.astype(np.int32)
        if points is not None:
            points = points.astype(np.float32) * min_scale
            points[:, 0] += append_w
            points[:, 1] += append_h
            points = points.astype(np.int32)
        return img_new, boxes, points    


    #转换回去不失真的点到原图像
    def def_convert(self, current_size, target_size, points):
        max_value = max(target_size)
        w, h = current_size
        scale = max_value / w
        
        points *= scale
        t_w, t_h = target_size
        w_offset, h_offset = abs(t_w - max_value) / 2, abs(t_h - max_value) / 2
        
        points[:, :, 0] -= w_offset
        points[:, :, 1] -= h_offset
        
        return points.astype(np.int32)